<template>
  <div class="production-plan">
    <div class="page-header">
      <h1 class="page-title">生产计划</h1>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增
        </el-button>
        <el-button @click="handleExport" :loading="exportLoading">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form :model="searchForm" inline>
        <el-form-item label="计划单号">
          <el-input 
            v-model="searchForm.planNumber" 
            placeholder="请输入计划单号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="计划主题">
          <el-input 
            v-model="searchForm.planSubject" 
            placeholder="请输入计划主题"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="单据日期">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select 
            v-model="searchForm.status" 
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option label="全部" value="" />
            <el-option label="草稿" value="draft" />
            <el-option label="已审核" value="approved" />
            <el-option label="执行中" value="executing" />
            <el-option label="已完成" value="completed" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table 
        :data="tableData" 
        v-loading="loading"
        stripe
        style="width: 100%"
        empty-text="暂无数据"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="planNumber" label="计划单号" width="150" />
        <el-table-column prop="planSubject" label="计划主题" min-width="200" />
        <el-table-column prop="documentDate" label="单据日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.documentDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="salesOrderSubject" label="销售订单主题" min-width="150" />
        <el-table-column prop="projectName" label="关联项目" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" min-width="150" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleView(row)"
            >
              查看
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="pagination.pageIndex"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.totalCount"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Download, Search, Refresh } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { getDefaultYearRange } from '@/utils/dateUtils'
import {
  getProductionPlanPage,
  exportProductionPlan,
  deleteProductionPlan
} from '@/services/productionPlan'
import type { 
  ProductionPlanQueryDto, 
  ProductionPlanPageResult, 
  ProductionPlan 
} from '@/types/productionPlan'

// 响应式数据
const router = useRouter()
const loading = ref(false)
const exportLoading = ref(false)
const tableData = ref<ProductionPlan[]>([])
const dateRange = ref<[string, string]>(getDefaultYearRange(2025))

// 搜索表单
const searchForm = reactive<ProductionPlanQueryDto>({
  pageIndex: 1,
  pageSize: 10,
  planNumber: '',
  planSubject: '',
  documentDateStart: getDefaultYearRange(2025)[0],
  documentDateEnd: getDefaultYearRange(2025)[1],
  status: ''
})

// 分页信息
const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
  totalPages: 0
})

// 计算属性：日期范围
const computedDateRange = computed(() => {
  if (dateRange.value) {
    return {
      documentDateStart: dateRange.value[0],
      documentDateEnd: dateRange.value[1]
    }
  }
  // 如果没有选择日期范围，使用默认值
  return {
    documentDateStart: searchForm.documentDateStart,
    documentDateEnd: searchForm.documentDateEnd
  }
})

// 获取生产计划数据
const fetchData = async () => {
  loading.value = true
  try {
    const query: ProductionPlanQueryDto = {
      ...searchForm,
      ...computedDateRange.value
    }
    
    console.log('查询参数:', query)
    const response = await getProductionPlanPage(query)
    
    if (response.code === 200) {
      tableData.value = response.data.items
      pagination.totalCount = response.data.totalCount
      pagination.totalPages = response.data.totalPages
      pagination.pageIndex = response.data.pageIndex
      pagination.pageSize = response.data.pageSize
      
      if (response.data.items.length === 0) {
        ElMessage.info('暂无数据')
      }
    } else {
      ElMessage.error(response.msg || '获取数据失败')
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败，请重试')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.pageIndex = 1
  searchForm.pageIndex = 1
  fetchData()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    pageIndex: 1,
    pageSize: 10,
    planNumber: '',
    planSubject: '',
    documentDateStart: getDefaultYearRange(2025)[0],
    documentDateEnd: getDefaultYearRange(2025)[1],
    status: ''
  })
  dateRange.value = getDefaultYearRange(2025)
  fetchData()
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.pageIndex = 1
  searchForm.pageSize = size
  searchForm.pageIndex = 1
  fetchData()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.pageIndex = page
  searchForm.pageIndex = page
  fetchData()
}

// 新增生产计划
const handleAdd = () => {
  router.push('/create-production-plan')
}

// 查看
const handleView = (row: ProductionPlan) => {
  router.push(`/production-plan/${row.id}`)
}

// 删除
const handleDelete = async (row: ProductionPlan) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除生产计划"${row.planSubject}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await deleteProductionPlan(row.id)
    
    if (response.code === 200 && response.data) {
      ElMessage.success('删除成功')
      // 重新获取数据
      fetchData()
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请重试')
    }
  }
}

// 导出
const handleExport = async () => {
  try {
    exportLoading.value = true
    const query: ProductionPlanQueryDto = {
      ...searchForm,
      ...computedDateRange.value
    }
    
    console.log('导出参数:', query)
    const blob = await exportProductionPlan(query)
    
    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `生产计划_${new Date().toISOString().split('T')[0]}.xlsx`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error(error instanceof Error ? error.message : '导出失败，请重试')
  } finally {
    exportLoading.value = false
  }
}

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return ''
  try {
    return new Date(dateStr).toLocaleDateString('zh-CN')
  } catch {
    return dateStr
  }
}

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    draft: 'info',
    approved: 'success',
    executing: 'warning',
    completed: 'success'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    draft: '草稿',
    approved: '已审核',
    executing: '执行中',
    completed: '已完成'
  }
  return statusMap[status] || status
}

// 组件挂载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.production-plan {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 120px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.table-section {
  background: white;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.pagination-section {
  display: flex;
  justify-content: center;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #333;
  font-weight: 600;
}

:deep(.el-table td) {
  color: #666;
}

:deep(.el-pagination) {
  justify-content: center;
}

:deep(.el-table__empty-block) {
  min-height: 200px;
}

:deep(.el-table__empty-text) {
  color: #909399;
  font-size: 14px;
}
</style> 